/**
 * Project SearchEngine
 */


#include "PageLib.h"
#include "Configuration.h"

/**
 * PageLib implementation
 */

/* PageLib::PageLib(Configuration& conf, DirScanner& DirScanner, */
/*             FileProcessor& FileProcessor) */
PageLib::PageLib()
: _dirScanner()
, _fileProcessor(4000)
{
    /* cout << "filename: " << _filename << endl; */
}
PageLib::~PageLib()
{

}

void PageLib::create(const string& dirname)
{
    cout << "page.size(): " << _pages.size() << endl;
    //走FileProcessor构造函数
    /* FileProcessor filePro(4000, _filename); //写成"_filename"报的错 */
    _dirScanner(dirname);
    _files = _dirScanner.getFiles();
    vector<string>::iterator it ;
    vector<RSSItem>::iterator itTmp;
    cout << "444" << endl;
    for (it = _files.begin(); it != _files.end(); ++it) {
        cout << *it << endl;
        //传一个文件名路径过去格式化好
        vector<RSSItem> tmp =  _fileProcessor.read(*it);

        // 格式化好的内容有分别写入PageLib中的容器--vector 没有operator+= ()
        for (itTmp = tmp.begin(); itTmp != tmp.end(); ++itTmp) {
            _pages.push_back(*itTmp);
        }

    }
    /* _pages = _fileProcessor.read(); */ 
    cout << "page.size(): " << _pages.size() << endl;
}


// 写入磁盘
void PageLib::store()
{
    const string filename = "data/ripepage.dat";
    const string offsetFilename = "data/offset.dat";
    ofstream ofs(filename);
    ofstream ofsOffset(offsetFilename);
    // ofs 是对,怎么可以if (!ofs)
    if (!ofs) {
        // 一定是ofstream 重载了！，opereator!()
        std::cerr << " open " << filename << " faile! " << endl;
        return;
    }
    if (!ofsOffset) {
        // 一定是ofstream 重载了！，opereator!()
        std::cerr << " open " << offsetFilename << " faile! " << endl;
        return;
    }

    size_t docBegin = 0;
    size_t docLength = 0;
    for (size_t idx = 0; idx != _pages.size(); ++idx) {
        ofs << "<doc><docid>" << idx + 1
            << "</docid><title>" << _pages[idx]._title
            << "</title><link>" << _pages[idx]._link
            << "</link><description>" << _pages[idx]._description
        << "</description><content" << _pages[idx]._content << "</content></doc>";
        ofs << "\n" ;

        // 计算文章位置偏移
        docLength = ofs.tellp(); //直接减好像类型不匹配的问题
        docLength -= docBegin;
        /* cout << "docLength  " << docLength << endl; */
        _offsetLib[idx +1] = make_pair(docBegin, docLength);
        /* cout << "_offsetLib.first" << _offsetLib[idx + 1].first << endl; */
        docBegin += docLength;
        //写入offset.dat
        ofsOffset << idx + 1 << "  "
            << _offsetLib[idx + 1].first << "  "
            << _offsetLib[idx + 1].second << "  ";
        ofsOffset << "\n";
    }

    // 关闭流才会刷新文件缓冲区，把内容写到文件中哦----重要
    ofs.close();
}
